package org.tekmob.remindpal.controller;

import java.util.Calendar;
import java.util.List;

import org.tekmob.remindpal.R;
import org.tekmob.remindpal.model.Reminder;
import org.tekmob.remindpal.model.ReminderDAO;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
/**
 * This activity will be called when 
 * Option Menu "Add Reminder" clicked
 * 
 * When button "Add" clicked, triggered Alarm
 * 
 * @author Annisa
 *
 */
public class NewReminder extends Activity {

	//private static final int PICK_RINGTONE = 1;
	public TimePicker timePicker;
	public Calendar cal;
	public ReminderDAO dao;
	Calendar mcurrentTime;
	int hour;
	int minute;
	//Initiate Reminder Column
	int _id;
	String _name;
	int _date;
	int _month;
	int _year;
	int _hour;
	int _minute;
	String _sound;
	String _vibrate="false";
	String _increase="false";
	String _move="false";
	String _shake="false";

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.activity_new_reminder);

		cal = Calendar.getInstance();

		//Setting Name
		final EditText name = (EditText) findViewById(R.id.name);

		//Setting Time
		final EditText time = (EditText)findViewById(R.id.time) ;
		time.setOnClickListener(new OnClickListener() {

			/*
			 * On Click, show time picker
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar mcurrentTime = Calendar.getInstance();
				int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
				int minute = mcurrentTime.get(Calendar.MINUTE);
				TimePickerDialog mTimePicker = new TimePickerDialog(NewReminder.this, new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
						time.setText( "" + selectedHour + ":" + selectedMinute);
						cal.set(Calendar.HOUR_OF_DAY, selectedHour);
						cal.set(Calendar.MINUTE, selectedMinute);
						_hour = selectedHour;
						_minute = selectedMinute;
					}
				}, hour, minute, true);
				mTimePicker.setTitle("Select Time");
				mTimePicker.show();

			}
		});

		//Setting Date
		final Spinner date = (Spinner)findViewById(R.id.choose_date);
		String[] itemsDate = {"", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
				"11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
				"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
		ArrayAdapter<String> dateList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsDate);
		dateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		date.setAdapter(dateList);


		//Setting Month
		final Spinner month = (Spinner)findViewById(R.id.choose_month);
		String[] itemsMonth = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September",
				"October", "November", "December"};
		ArrayAdapter<String> monthList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsMonth);
		monthList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		month.setAdapter(monthList);

		//Setting Year
		final Spinner year = (Spinner)findViewById(R.id.choose_year);
		String[] itemsYear = { "", "2013", "2014", "2015"};
		ArrayAdapter<String> yearList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsYear);
		yearList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		year.setAdapter(yearList);

		//Setting Sound
		final Spinner sound = (Spinner)findViewById(R.id.choose_sound);
		String[] items2 = {"","From Gallery", "Record Audio"};
		ArrayAdapter<String> soundList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items2);
		soundList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sound.setAdapter(soundList);
		sound.setOnItemSelectedListener (new MyOnItemSelectedListener());
		
		/*RingtoneManager mRingtoneManager = new RingtoneManager(this); //adds ringtonemanager
	    mRingtoneManager.setType(RingtoneManager.TYPE_RINGTONE); //sets the type to ringtones
	    mRingtoneManager.setIncludeDrm(true); //get list of ringtones to include DRM

	    Cursor mCursor = mRingtoneManager.getCursor();//appends my cursor to the ringtonemanager
	    startManagingCursor(mCursor); //starts the cursor query
	    String[] from = {mCursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX)}; // get the list items for the listadapter could be TITLE or URI

	    int[] to = {android.R.id.text1};

	    // create simple cursor adapter
	    SimpleCursorAdapter adapter =
	      new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mCursor, from, to );
	    adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
	    // get reference to our spinner
	    sound.setAdapter(adapter);
		Intent i = getIntent();
		String fileName = i.getStringExtra("FILE");
*/

		//Check list Vibrate
		final CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate);
		vibrate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(vibrate.isChecked()) {
					_vibrate = "true";
				} else _vibrate = "false";
			}

		});

		//Check list increasing Sound
		final CheckBox increase = (CheckBox) findViewById(R.id.increasing_sound);
		increase.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(increase.isChecked()) {
					_increase = "true";
				} else _increase = "false";
			}

		});

		//Check list Move
		final CheckBox move = (CheckBox) findViewById(R.id.check_move);
		move.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(move.isChecked()) {
					_move = "true";
				} else _move = "false";
			}

		});

		//Shake to Stop
		final CheckBox shake = (CheckBox) findViewById(R.id.check_shake);
		shake.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(shake.isChecked()) {
					_shake = "true";
				} else _shake = "false";
			}

		});

		//Click button "Add Reminder"
		Button add = (Button) findViewById(R.id.addReminder);
		add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				_name = name.getText().toString();
				_date = Integer.parseInt(date.getSelectedItem().toString());
				if (month.getSelectedItem().toString()== "January") {
					_month = 0;
				} else if (month.getSelectedItem().toString()== "February") {
					_month = 1;
				} else if (month.getSelectedItem().toString()== "March") {
					_month = 2;
				} else if (month.getSelectedItem().toString()== "April") {
					_month = 3;
				} else if (month.getSelectedItem().toString()== "May") {
					_month = 4;
				} else if (month.getSelectedItem().toString()== "June") {
					_month = 5;
				} else if (month.getSelectedItem().toString()== "July") {
					_month = 6;
				} else if (month.getSelectedItem().toString()== "August") {
					_month = 7;
				} else if (month.getSelectedItem().toString()== "September") {
					_month = 8;
				} else if (month.getSelectedItem().toString()== "October") {
					_month = 9;
				} else if (month.getSelectedItem().toString()== "November") {
					_month = 10;
				} else if (month.getSelectedItem().toString()== "December") {
					_month = 11;
				} 
				_year = Integer.parseInt(year.getSelectedItem().toString());
				_sound = sound.getSelectedItem().toString();
				
				// Initiate database
				dao = new ReminderDAO(NewReminder.this);
				//Create into database
				//Check ID 
				_id = 5 + (int)(Math.random() * ((2000 - 5) + 1));
				List<Reminder> checkID = dao.getReminder();
				for (int i = 0; i < checkID.size(); i++) {
					if (checkID.get(i).getId()== _id) {
						_id = 5 + (int)(Math.random() * ((200 - 5) + 1));
					}
				}
				dao.createReminder(_id, _name, _date, _month, _year,
						_hour, _minute, _sound, _vibrate, _increase, _move, _shake);

				//Create an offset from the current time in which the alarm will go off.
				cal.set(Calendar.YEAR, _year);
				cal.set(Calendar.MONTH, _month);
				cal.set(Calendar.DAY_OF_MONTH, _date);

				//Create a new PendingIntent and add it to the AlarmManager
				Intent intent = new Intent(NewReminder.this, AlarmReceiverActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(NewReminder.this,
						_id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
				AlarmManager am = 
						(AlarmManager) NewReminder.this.getSystemService(Activity.ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
						pendingIntent);
				
				
				/*Intent triggerAlarm = new Intent(getApplicationContext(),SettingAlarm.class);
				startActivity(triggerAlarm);*/
				
				// Display success information
				Toast.makeText(getApplicationContext(), "New reminder added!", Toast.LENGTH_LONG).show();
				Intent intent2 = new Intent(getApplicationContext(),ShowReminder.class);
				startActivity(intent2);

			}

		});

	}

	/*
	 * Initiate Option Menu
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list_reminder, menu);
		return true;

	}

	/*
	 * Handler when item selected
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()) {
		case R.id.new_reminder:
			//click on create item
			Intent newReminder = new Intent(getApplicationContext(),NewReminder.class);
			startActivity(newReminder);
			break; 
		case R.id.show:
			//click on show item
			Intent showReminder = new Intent(getApplicationContext(),ShowReminder.class);
			startActivity(showReminder);
			break;
		case R.id.send:
			//click on send item
			Intent sendReminder = new Intent(getApplicationContext(),SendReminder.class);
			startActivity(sendReminder);
			break;
		}
		return true;	    
	}
	
	/*
	 * Setting when sound spinner item selected
	 */
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

			if(parent.getItemAtPosition(pos).toString() == "From Gallery") {
				//Choose ringtone
				Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
				tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
				startActivityForResult(tmpIntent, 0);
			}

			if(parent.getItemAtPosition(pos).toString() == "Record Audio") {
				//Record audio 
				/*Intent record = new Intent(getApplicationContext(),AndroidAudioRecordActivity.class);
				startActivity(record);*/
				Intent record = new Intent(getApplicationContext(),AudioRecordingActivity.class);
				startActivity(record);
			}
		}

		public void onNothingSelected(AdapterView<?> parent)  {
			// Do nothing.
		}
	}
}